package org.br.erp.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.br.erp.base.entity.*;
import org.br.erp.base.mapper.*;
import org.br.erp.base.service.IMaterialService;
import org.br.erp.base.service.IMaterialtypeService;
import org.br.erp.base.service.IScmuomService;
import org.br.erp.base.utils.ERPUtils;
import org.br.erp.base.vo.MaterialImportVo;
import org.br.erp.base.vo.MaterialPage;
import org.br.erp.base.vo.MaterialVo;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.Bidi;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Random;
import java.util.stream.Collectors;

/**
 * @Description: 产品表
 * @Author: jeecg-boot
 * @Date:   2022-08-20
 * @Version: V1.0
 */
@Service
public class MaterialServiceImpl extends ServiceImpl<MaterialMapper, Material> implements IMaterialService {

    @Autowired
    MaterialMapper materialMapper;

    @Autowired
    MaterialSaleMapper materialSaleMapper;

    @Autowired
    MaterialPoMapper materialPoMapper;

    @Autowired
    MaterialMaufMapper materialMaufMapper;

    @Autowired
    MaterialStockMapper materialStockMapper;

    @Autowired
    MaterialUnitConvetMapper materialUnitConvetMapper;

    @Autowired
    private IScmuomService scmuomService;

    @Autowired
    private MaterialSecAttrMapper materialSecAttrMapper;

    @Autowired
    private MaterialAndSecMaterialMapper materialAndSecMaterialMapper;


    @Autowired
    private IMaterialtypeService materialtypeService;

    @Override
    public List<Material> getMaterialByMatrerialTypeid(String materialTypeid) {
        return materialMapper.getMaterialsByMaterialTypeid(materialTypeid);
    }

    @Override
    public Material getMaterialbyMaterialId(String materialid) {
        return materialMapper.getMaterialByMaterialId(materialid);
    }

    @Override
    @Transactional
    public void updatestatus(List<String> ids, String statusFlag) {
        materialMapper.selectBatchIds(ids).forEach(item->{
            item.setEnablestatus(statusFlag);
            materialMapper.updateById(item);
        });
    }

    @Override
    @Transactional
    public void saveMainObject(MaterialPage materialPage) {
        Material material=new Material();
        BeanUtils.copyProperties(materialPage,material);


        if(material.getIskitflag()!=null && material.getIskitflag().equalsIgnoreCase("true")){
            //套件销售
            String ispd = material.getIspd();

            String isgd = material.getIsgd();

            if((ispd!=null && ispd.equalsIgnoreCase("truue")) ||(isgd!=null && isgd.equalsIgnoreCase("true"))){
                throw new RuntimeException("当前物料是套件物料，不允许被库存或生产");
            }
        }

        material.setSecattmatflag("0");

        materialMapper.insert(material);

         Materialpo materialPo=null;
         Materialsale materialsale=null;
         Materialstock materialstock=null;


        List<MaterialUnitConvet> materialUnitConveList = materialPage.getMaterialUnitConvetList();

        checkuomifexist(material, materialPo, materialsale, materialstock, materialUnitConveList);

        for (MaterialUnitConvet materialUnitConvet : materialUnitConveList) {
            materialUnitConvet.setParentid(material.getId());
            materialUnitConvetMapper.insert(materialUnitConvet);
        }

        List<Materialmauf> materialmaufList = materialPage.getMaterialmaufList();
        for (Materialmauf materialmauf : materialmaufList) {
            materialmauf.setParentid(material.getId());
            materialMaufMapper.insert(materialmauf);
            updateMaterialInfoByMaufInfo(materialmauf, material);
        }


        List<Materialsale> materialSaleList = materialPage.getMaterialSaleList();
        if(materialSaleList!=null && materialSaleList.size()>0) {
            materialsale = materialSaleList.get(0);
            if (ERPUtils.isNoneOrEmpty(materialsale.getSaleuomid())) {
                materialsale.setSaleuomid(material.getUom());
            }
            materialsale.setParentid(material.getId());
            materialSaleMapper.insert(materialsale);
        }else{
            if(material.getIssale().equalsIgnoreCase("true")){
                Materialsale newsales=new Materialsale();
                newsales.setParentid(material.getId());
                newsales.setSaleuomid(material.getUom());
                materialSaleMapper.insert(newsales);

            }
        }
        List<Materialpo> materialPoList = materialPage.getMaterialPoList();
        if(materialPoList!=null && materialPoList.size()>0){
            materialPo =materialPoList.get(0);
            materialPo.setParentid(material.getId());
            if(ERPUtils.isNoneOrEmpty(materialPo.getPouomid())){
                materialPo.setPouomid(material.getUom());
            }
            materialPoMapper.insert(materialPo);
        }else if(material.getIspo().equalsIgnoreCase("true")){
            Materialpo materialpo=new Materialpo();
            materialpo.setParentid(material.getId());
            materialpo.setPouomid(material.getUom());
            materialPoMapper.insert(materialpo);
        }

        List<Materialstock> materialStockList = materialPage.getMaterialStockList();
        if(materialStockList!=null && materialStockList.size()>0){
            materialstock=materialStockList.get(0);
            materialstock.setParentid(material.getId());
            if(ERPUtils.isNoneOrEmpty(materialstock.getStockuomid())){
                materialstock.setStockuomid(material.getUom());
            }
            materialStockMapper.insert(materialstock);
        }else if(material.getIsgd().equalsIgnoreCase("true")){
            Materialstock materialstock1=new Materialstock();
            materialstock1.setParentid(material.getId());
            materialstock1.setStockuomid(material.getUom());
            materialStockMapper.insert(materialstock1);
        }


        List<MaterialSecAttr> materialSecAttrList = materialPage.getMaterialSecAttrList();
        int i=1;


        for (MaterialSecAttr materialSecAttr : materialSecAttrList) {
            materialSecAttr.setParentid(material.getId());
            materialSecAttr.setMaterialname(material.getMaterialname());
            materialSecAttr.setMaterialcode(material.getMaterialcode()+"_"+i);
            i++;
            materialSecAttrMapper.insert(materialSecAttr);

            //同时生成一个新的辅助分录物料,用于记录当前物料与辅助分录的关系
            generateSecMaterial(materialSecAttr, material);

        }

    }

    @Transactional
    private void updateMaterialInfoByMaufInfo(Materialmauf materialmauf, Material material) {
        if(materialmauf.getIssale()!=null && materialmauf.getIssale().equalsIgnoreCase("Y")){
            material.setIssale("true");
        }else{
            material.setIssale("false");
        }
        if(materialmauf.getIspo()!=null && materialmauf.getIspo().equalsIgnoreCase("Y")){
            material.setIspo("true");
        }else{
            material.setIspo("false");
        }
        if(materialmauf.getIspd()!=null && materialmauf.getIspd().equalsIgnoreCase("Y")){
            material.setIspd("true");
        }else{
            material.setIspo("false");
        }
        if(materialmauf.getIskitflag()!=null && materialmauf.getIskitflag().equalsIgnoreCase("Y")){
            material.setIskitflag("true");
        }else{
            material.setIskitflag("false");
        }

        if(materialmauf.getIsgd()!=null && materialmauf.getIsgd().equalsIgnoreCase("Y")){
            material.setIsgd("true");
        }else{
            material.setIsgd("false");
        }

        if(materialmauf.getN1()!=null){
            material.setN1(materialmauf.getN1())
;            }
        if(materialmauf.getN2()!=null){
            material.setN2(materialmauf.getN2());
        }

        if(material.getEnablestatus()==null){
            material.setEnablestatus("0");
        }

        materialMapper.updateById(material);
    }

    private void generateSecMaterial(MaterialSecAttr materialSecAttr, Material material) {
        Material secMaterial = new Material();
        BeanUtils.copyProperties(material,secMaterial);
        secMaterial.setId(null);
        secMaterial.setMatimgsrc(materialSecAttr.getSecimgsrc());
        secMaterial.setMaterialcode(secMaterial.getMaterialcode()+"_"+ new Random().nextInt(1000));
        secMaterial.setSecattmatflag("1");
        secMaterial.setSecattr1("false");
        secMaterial.setSecattr2("false");
        secMaterial.setSecattr3("false");
        secMaterial.setSecattr4("false");
        secMaterial.setSecattr5("false");
        materialMapper.insert(secMaterial);

        MaterialAndSecMaterial materialAndSecMaterial=new MaterialAndSecMaterial();
        materialAndSecMaterial.setMaterialid(material.getId());
        materialAndSecMaterial.setSecmaterialid(secMaterial.getId());
        materialAndSecMaterialMapper.insert(materialAndSecMaterial);
    }

    /**
     * 判断计量单位换算率是否存在
     * @param material
     * @param materialPo
     * @param materialsale
     * @param materialstock
     * @param materialUnitConveList
     */
    private void checkuomifexist(Material material, Materialpo materialPo, Materialsale materialsale, Materialstock materialstock, List<MaterialUnitConvet> materialUnitConveList) {
        if(materialPo !=null){
            String posecuomid = materialPo.getPosecuomid();
            String pouomid = materialPo.getPouomid();
            checkUnitConvertIfExist(materialUnitConveList,pouomid, material.getUom(),"PO");
            if(posecuomid!=null && !posecuomid.equalsIgnoreCase("")){
                checkUnitConvertIfExist(materialUnitConveList,posecuomid, material.getUom(),"PO");
            }
        }

        if(materialsale !=null){
            String saleuomid = materialsale.getSaleuomid();
            String salesecuomid = materialsale.getSalesecuomid();
            checkUnitConvertIfExist(materialUnitConveList,saleuomid, material.getUom(),"SALE");
            if(salesecuomid!=null && !salesecuomid.equalsIgnoreCase("")){
                checkUnitConvertIfExist(materialUnitConveList,salesecuomid, material.getUom(),"SALE");
            }
        }

        if(materialstock !=null){
            String stockuomid = materialstock.getStockuomid();
            String stocksecuomid = materialstock.getStocksecuomid();
            checkUnitConvertIfExist(materialUnitConveList,stockuomid, material.getUom(),"STOCK");
            if(stocksecuomid!=null && !stocksecuomid.equalsIgnoreCase("")){
                checkUnitConvertIfExist(materialUnitConveList,stocksecuomid, material.getUom(),"STOCK");
            }
        }
    }

    private void checkUnitConvertIfExist(List<MaterialUnitConvet> materialUnitConvets,String unitScopeId,String mainUnitId,String unitScope){
        if(unitScopeId.equalsIgnoreCase(mainUnitId)){
            return;
        }
        //检查第一个计量单位
        List<MaterialUnitConvet> collect = materialUnitConvets.stream().filter(item -> item.getFirstunitid().equalsIgnoreCase(unitScopeId)).collect(Collectors.toList());
        List<MaterialUnitConvet> collect1 = collect.stream().filter(item -> item.getSecunitid().equalsIgnoreCase(mainUnitId)).collect(Collectors.toList());

        //检查第二个计量单位
        List<MaterialUnitConvet> newCollect = materialUnitConvets.stream().filter(item -> item.getFirstunitid().equalsIgnoreCase(mainUnitId)).collect(Collectors.toList());
        List<MaterialUnitConvet> newCollect1 = newCollect.stream().filter(item -> item.getSecunitid().equalsIgnoreCase(unitScopeId)).collect(Collectors.toList());

        if(collect1.size()==0 && newCollect1.size() == 0){
            if(unitScope.equalsIgnoreCase("PO")) {
                throw new RuntimeException("请先定义当前基本主计量单位和采购计量单位的换算率");
            }
            if(unitScope.equalsIgnoreCase("SALE")){
                throw new RuntimeException("请先定义当前基本主计量单位和销售计量单位的换算率");
            }
            if(unitScope.equalsIgnoreCase("STOCK")){
                throw new RuntimeException("请先定义当前基本主计量单位和库存计量单位的换算率");
            }
        }
        if(collect1.size()>1 || newCollect1.size() > 1){
            if(unitScope.equalsIgnoreCase("PO")) {
                throw new RuntimeException("不允许定义当前主计量单位和采购计量单位多个换算率");
            }
            if(unitScope.equalsIgnoreCase("SALE")){
                throw new RuntimeException("不允许定义当前主计量单位和销售计量单位多个换算率");
            }
            if(unitScope.equalsIgnoreCase("STOCK")){
                throw new RuntimeException("不允许定义当前主计量单位和库存计量单位多个换算率");
            }
        }
    }

    @Override
    public List<Materialsale> getMaterisaleByMaterialid(String materialid) {
        QueryWrapper<Materialsale> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parentid",materialid);
        List<Materialsale> materialsales = materialSaleMapper.selectList(queryWrapper);
        return materialsales;
    }

    @Override
    public List<Materialpo> getMaterialpoByMaterialid(String materialid) {
        QueryWrapper<Materialpo> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parentid",materialid);
        List<Materialpo> materialpos = materialPoMapper.selectList(queryWrapper);
        return materialpos;
    }

    @Override
    public List<Materialmauf> getMaterialmaufByMaterialid(String materialid) {
        QueryWrapper<Materialmauf> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parentid",materialid);
        List<Materialmauf> materialmaufs = materialMaufMapper.selectList(queryWrapper);
        return materialmaufs;
    }

    @Override
    public List<Materialstock> getMaterialstockByMaterialid(String materialid) {
        QueryWrapper<Materialstock> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parentid",materialid);
        List<Materialstock> Materialstocks = materialStockMapper.selectList(queryWrapper);
        return Materialstocks;
    }

    @Override
    public List<MaterialUnitConvet> getMaterialUnitConvetByMaterialid(String materialid) {
        QueryWrapper<MaterialUnitConvet> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parentid",materialid);
        List<MaterialUnitConvet> materialUnitConvets = materialUnitConvetMapper.selectList(queryWrapper);
        return materialUnitConvets;
    }

    @Override
    @Transactional
    public void updateByMainId(MaterialPage materialPage) {
        Material material=new Material();
        BeanUtils.copyProperties(materialPage,material);

        materialMapper.updateById(material);

        Materialsale materialsale=null;
        Materialpo materialpo=null;
        Materialstock materialstock=null;
        if(materialPage.getMaterialSaleList()!=null && materialPage.getMaterialSaleList().size()>0){
            materialsale=new Materialsale();
            BeanUtils.copyProperties(materialPage.getMaterialSaleList().get(0),materialsale);
            materialsale.setParentid(material.getId());
//            if(getMaterisaleByMaterialid(material.getId()) == null
//                    || getMaterisaleByMaterialid(material.getId()).size() == 0){
//                materialSaleMapper.insert(materialsale);
//            }else {
//                materialSaleMapper.updateById(materialsale);
//            }
            materialSaleMapper.deleteById(materialsale.getId());
            materialSaleMapper.insert(materialsale);
        }else if(material.getIssale().equalsIgnoreCase("true")){
            materialsale=new Materialsale();
            materialsale.setParentid(material.getId());
            materialsale.setSaleuomid(material.getUom());
            materialSaleMapper.insert(materialsale);
        }
        if(materialPage.getMaterialPoList()!=null && materialPage.getMaterialPoList().size()>0){
            materialpo=new Materialpo();
            BeanUtils.copyProperties(materialPage.getMaterialPoList().get(0),materialpo);
            materialpo.setParentid(material.getId());
//            List<Materialpo> materialpoByMaterialid = getMaterialpoByMaterialid(material.getId());
//            if(materialpoByMaterialid!=null && materialpoByMaterialid.size()>0){
//                materialpoByMaterialid.stream().forEach(item->{
//                    materialPoMapper.deleteById(item.getId());
//                });
//            }
            materialPoMapper.deleteById(materialpo.getId());
            materialPoMapper.insert(materialpo);
        }else if(material.getIspo().equalsIgnoreCase("true")){
            materialpo=new Materialpo();
            materialpo.setParentid(material.getId());
        materialpo.setPouomid(material.getUom());
        materialPoMapper.insert(materialpo);
        }
        if(materialPage.getMaterialStockList()!=null && materialPage.getMaterialStockList().size()>0){
            materialstock=new Materialstock();
            BeanUtils.copyProperties(materialPage.getMaterialStockList().get(0),materialstock);
            materialStockMapper.deleteById(materialstock.getId());
            materialstock.setParentid(material.getId());
            materialStockMapper.insert(materialstock);
        }else if(material.getIsgd().equalsIgnoreCase("true")){
            materialstock=new Materialstock();
            materialstock.setParentid(material.getId());
            materialstock.setStockuomid(material.getUom());
            materialStockMapper.insert(materialstock);
        }

        if(materialPage.getMaterialmaufList()!=null && materialPage.getMaterialmaufList().size()>0){
            Materialmauf materialmauf=new Materialmauf();
            BeanUtils.copyProperties(materialPage.getMaterialmaufList().get(0),materialmauf);
            materialMaufMapper.deleteById(materialmauf);
            materialmauf.setParentid(material.getId());
            materialMaufMapper.insert(materialmauf);


            updateMaterialInfoByMaufInfo(materialmauf,material);
        }



        if(materialPage.getMaterialUnitConvetList()!=null && materialPage.getMaterialUnitConvetList().size()>0){
            List<MaterialUnitConvet> materialUnitConveList = materialPage.getMaterialUnitConvetList();
            checkuomifexist(material,materialpo,materialsale,materialstock,materialUnitConveList);

            for (MaterialUnitConvet materialUnitConvet : materialUnitConveList) {
                QueryWrapper<MaterialUnitConvet> queryWrapper=new QueryWrapper<>();
                queryWrapper.eq("parentid",material.getId());
                queryWrapper.eq("firstunitid",materialUnitConvet.getFirstunitid());
                queryWrapper.eq("secunitid",materialUnitConvet.getSecunitid());
                materialUnitConvetMapper.delete(queryWrapper);
                materialUnitConvet.setParentid(material.getId());
                materialUnitConvetMapper.insert(materialUnitConvet);
            }
        }

        if(materialPage.getMaterialSecAttrList().size()>0){
            List<MaterialSecAttr> materialSecAttrList = materialPage.getMaterialSecAttrList();
            int i=1;
            for (MaterialSecAttr materialSecAttr : materialSecAttrList) {
                materialSecAttr.setParentid(material.getId());
                materialSecAttr.setMaterialcode(material.getMaterialcode()+"_"+i);
                materialSecAttr.setMaterialname(material.getMaterialname());
                i++;

                if(materialSecAttr.getId()==null){
                    materialSecAttrMapper.insert(materialSecAttr);
                }else {
                    MaterialSecAttr materialSecAttr1 = materialSecAttrMapper.selectById(materialSecAttr.getId());
                    if(materialSecAttr1!=null) {
                        materialSecAttrMapper.updateById(materialSecAttr);
                    }else{
                        materialSecAttrMapper.insert(materialSecAttr);
                    }
                }
                deleteSecMaterial(material);
                generateSecMaterial(materialSecAttr,material);
            }
        }
    }

    private void deleteSecMaterial(Material material) {
        //先去删除之前的辅助分类物料
        QueryWrapper<MaterialAndSecMaterial> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("materialid", material.getId());
        List<MaterialAndSecMaterial> materialAndSecMaterials = materialAndSecMaterialMapper.selectList(queryWrapper);
        materialAndSecMaterials.forEach(item->{
            materialMapper.deleteById(item.getSecmaterialid());
        });
    }

    @Override
    public MaterialVo getMaterialVoInfoByMaterialID(String MID) {
        MaterialVo materialVo=new MaterialVo();
//        Material material = materialMapper.selectById(materialID);
        QueryWrapper<Material> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("id",MID).or(item->item.eq("materialcode",MID));
        List<Material> materials = materialMapper.selectList(queryWrapper);
        if(materials.size() == 0 ){
            return null;
        }
        Material material = materials.get(0);
        if(material==null)
            return null;
        String materialID = material.getId();
        BeanUtils.copyProperties(material,materialVo);

        QueryWrapper<Materialsale> materialsaleQueryWrapper=new QueryWrapper<>();
        materialsaleQueryWrapper.eq("parentid",materialID);
        List<Materialsale> materialsales = materialSaleMapper.selectList(materialsaleQueryWrapper);
        if(materialsales!=null && materialsales.size()>0){
            BeanUtils.copyProperties(materialsales.get(0),materialVo);
        }

        QueryWrapper<Materialpo> materialpoQueryWrapper=new QueryWrapper<>();
        materialpoQueryWrapper.eq("parentid",materialID);
        List<Materialpo> materialpos = materialPoMapper.selectList(materialpoQueryWrapper);
        if(materialpos!=null && materialpos.size()>0){
            BeanUtils.copyProperties(materialpos.get(0),materialVo);
        }

        QueryWrapper<Materialstock> materialstockQueryWrapper=new QueryWrapper<>();
        materialstockQueryWrapper.eq("parentid",materialID);
        List<Materialstock> materialstocks = materialStockMapper.selectList(materialstockQueryWrapper);
        if(materialstocks!=null && materialstocks.size()>0){
            BeanUtils.copyProperties(materialstocks.get(0),materialVo);
        }

        QueryWrapper<Materialmauf> materialmaufQueryWrapper=new QueryWrapper<>();
        materialmaufQueryWrapper.eq("parentid",materialID);
        List<Materialmauf> materialmaufs = materialMaufMapper.selectList(materialmaufQueryWrapper);
        if(materialmaufs!=null && materialmaufs.size()>0){
            materialVo.setMaufbatchrule(materialmaufs.get(0).getBatchrule());
            materialVo.setMaufbatch(materialmaufs.get(0).getMaufbatch());
            materialVo.setMaufbddays(materialmaufs.get(0).getMaufbddays());
            materialVo.setMauffixdays(materialmaufs.get(0).getMauffixdays());
        }

        materialVo.setId(materialID);

        QueryWrapper<MaterialSecAttr> secAttrQueryWrapper=new QueryWrapper<>();
        secAttrQueryWrapper.eq("parentid",material.getId());

        List<MaterialSecAttr> materialSecAttrs = materialSecAttrMapper.selectList(secAttrQueryWrapper);

        materialVo.setMaterialSecAttrList(materialSecAttrs);

        return materialVo;

    }



    @Override
    public List<MaterialVo> getMaterialVoInfosByMaterialIds(List<String> materialids) {
        QueryWrapper<Material> queryWrapper=new QueryWrapper<>();
        queryWrapper.in("id",materialids);
        List<Material> materials = materialMapper.selectList(queryWrapper);
        if(materials.size() == 0){
            return null;
        }

        List<MaterialVo> res=new ArrayList<>();
        for (Material material : materials) {
            MaterialVo materialVo=new MaterialVo();
            BeanUtils.copyProperties(material,materialVo);

            QueryWrapper<Materialsale> materialsaleQueryWrapper=new QueryWrapper<>();
            materialsaleQueryWrapper.eq("parentid",material.getId());
            List<Materialsale> materialsales = materialSaleMapper.selectList(materialsaleQueryWrapper);
            if(materialsales!=null && materialsales.size()>0){
                BeanUtils.copyProperties(materialsales.get(0),materialVo);
            }

            QueryWrapper<Materialpo> materialpoQueryWrapper=new QueryWrapper<>();
            materialpoQueryWrapper.eq("parentid",material.getId());
            List<Materialpo> materialpos = materialPoMapper.selectList(materialpoQueryWrapper);
            if(materialpos!=null && materialpos.size()>0){
                BeanUtils.copyProperties(materialpos.get(0),materialVo);
            }

            QueryWrapper<Materialstock> materialstockQueryWrapper=new QueryWrapper<>();
            materialstockQueryWrapper.eq("parentid",material.getId());
            List<Materialstock> materialstocks = materialStockMapper.selectList(materialstockQueryWrapper);
            if(materialstocks!=null && materialstocks.size()>0){
                BeanUtils.copyProperties(materialstocks.get(0),materialVo);
            }

            materialVo.setId(material.getId());

            QueryWrapper<MaterialUnitConvet> materialUnitConvetQueryWrapper=new QueryWrapper<>();
            materialUnitConvetQueryWrapper.eq("parentid",material.getId());
            List<MaterialUnitConvet> materialUnitConvets = materialUnitConvetMapper.selectList(materialUnitConvetQueryWrapper);
            materialVo.setMaterialUnitConvets(materialUnitConvets);

            QueryWrapper<Materialmauf> materialmaufQueryWrapper=new QueryWrapper<>();
            materialmaufQueryWrapper.eq("parentid",material.getId());
            List<Materialmauf> materialmaufs = materialMaufMapper.selectList(materialmaufQueryWrapper);
            if(materialmaufs.size()>0){
                materialVo.setMaufbatch(materialmaufs.get(0).getMaufbatch());
                materialVo.setMauffixdays(materialmaufs.get(0).getMauffixdays());
                materialVo.setMaufbddays(materialmaufs.get(0).getMaufbddays());
                materialVo.setMaufdays(materialmaufs.get(0).getMaufdays());
            }

            res.add(materialVo);
        }

        return res;
    }


    @Override
    public BigDecimal getMaterialSecQty(String materialid, BigDecimal qty,String firstuomid, String secuomid) {

        if(firstuomid==null){
            return qty;
        }
        if(firstuomid.equalsIgnoreCase(secuomid)){
            return qty;
        }

        //先去获取物料的基本计量单位
        Material material = materialMapper.selectById(materialid);
        if(material==null){
            return BigDecimal.ZERO;
        }
        //基本计量单位
        String baseUom = material.getUom();

        QueryWrapper<MaterialUnitConvet> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parentid",materialid);
        List<MaterialUnitConvet> materialUnitConvets = materialUnitConvetMapper.selectList(queryWrapper);
        if(materialUnitConvets.size()==0){
            return BigDecimal.ZERO;
        }
        if(firstuomid.equalsIgnoreCase(baseUom)) {
            List<MaterialUnitConvet> collect = materialUnitConvets.stream().filter(item -> item.getFirstunitid().equalsIgnoreCase(firstuomid)).collect(Collectors.toList());
            List<MaterialUnitConvet> collect1 = collect.stream().filter(item -> item.getSecunitid().equalsIgnoreCase(secuomid)).collect(Collectors.toList());
            if (collect1.size() == 1) {
                MaterialUnitConvet materialUnitConvet = collect1.get(0);
                String convetrule = materialUnitConvet.getConvetrule();
                BigDecimal firstunitnum = materialUnitConvet.getFirstunitnum();
                BigDecimal firstjd = materialUnitConvet.getFirstjd();
                BigDecimal secunitnum = materialUnitConvet.getSecunitnum();
                BigDecimal secjd = materialUnitConvet.getSecjd();
                if (firstunitnum.compareTo(BigDecimal.ZERO) == 0) {
                    throw new RuntimeException("当前物料计量单位换算率定义有问题，请查看物料定义");
                }
                if (convetrule.equalsIgnoreCase("") || convetrule.equalsIgnoreCase("GDHS")) {
                    //固定换算
                    //根据 firstnum * firstQty = secnum * secQty
                    //得到想要的辅数量
                    //   BigDecimal divide = qty.multiply(firstunitnum).divide(secunitnum, Integer.parseInt(secjd.toString()));
                    BigDecimal divide = qty.multiply(secunitnum).divide(firstunitnum, secjd.intValue());
                    return divide;
                } else if (convetrule.equalsIgnoreCase("FHHS")) {
                    //如果是复合计量单位
                    //判断复合计量单位是否有小数点，如果有小数点的话，将小数点的位置取出来进行单据处理来生成辅数量
                    String sqty = qty.toString();
                    if (sqty.contains(".")) {

                        int i = sqty.indexOf(".");
                        String orgqty = sqty.substring(0, i);
                        String subqty = sqty.substring(i, sqty.length());
                        // BigDecimal divide = ERPUtils.getBigDecimal(orgqty).multiply(firstunitnum).divide(secunitnum, Integer.parseInt(secjd.toString()));
                        BigDecimal divide = ERPUtils.getBigDecimal(orgqty).multiply(secunitnum).divide(firstunitnum, secjd.intValue());
                        BigDecimal multiply = ERPUtils.getBigDecimal(subqty).multiply(new BigDecimal(10));
                        divide = divide.add(multiply);
                        return divide;
                    } else {
                        BigDecimal divide = qty.multiply(secunitnum).divide(firstunitnum, secjd.intValue());
                        return divide;
                    }
                }
            }
        }else if(secuomid.equalsIgnoreCase(baseUom)){
            //辅计量单位等于主计量单位
            //则去查找基本主计量单位与现在的辅计量之间的关系
            //先去查找当前计量单位与基本主计量单位之间的换算率
            List<MaterialUnitConvet> collect2 = materialUnitConvets.stream().filter(item -> item.getFirstunitid().equalsIgnoreCase(baseUom)).collect(Collectors.toList());
            List<MaterialUnitConvet> collect3 = collect2.stream().filter(item -> item.getSecunitid().equalsIgnoreCase(firstuomid)).collect(Collectors.toList());
            if(collect3.size()==1){
                MaterialUnitConvet materialUnitConvet = collect3.get(0);
                String convetrule = materialUnitConvet.getConvetrule();
                BigDecimal firstunitnum = materialUnitConvet.getFirstunitnum();
                BigDecimal firstjd = materialUnitConvet.getFirstjd();
                BigDecimal secunitnum = materialUnitConvet.getSecunitnum();
                BigDecimal secjd = materialUnitConvet.getSecjd();
                if (firstunitnum.compareTo(BigDecimal.ZERO) == 0) {
                    throw new RuntimeException("当前物料计量单位换算率定义有问题，请查看物料定义");
                }
                if (convetrule.equalsIgnoreCase("GDHS")) {
                    //固定换算
                    //根据 firstnum * firstQty = secnum * secQty
                    //得到想要的辅数量
                    //   BigDecimal divide = qty.multiply(firstunitnum).divide(secunitnum, Integer.parseInt(secjd.toString()));
                    BigDecimal divide = qty.multiply(firstunitnum).divide(secunitnum, secjd.intValue());
                    return divide;
                } else if (convetrule.equalsIgnoreCase("FHHS")) {
                    //如果是复合计量单位
                    //判断复合计量单位是否有小数点，如果有小数点的话，将小数点的位置取出来进行单据处理来生成辅数量
                    String sqty = qty.toString();
                    if (sqty.contains(".")) {

                        int i = sqty.indexOf(".");
                        String orgqty = sqty.substring(0, i);
                        String subqty = sqty.substring(i, sqty.length());
                        // BigDecimal divide = ERPUtils.getBigDecimal(orgqty).multiply(firstunitnum).divide(secunitnum, Integer.parseInt(secjd.toString()));
                        BigDecimal divide = ERPUtils.getBigDecimal(orgqty).multiply(secunitnum).divide(firstunitnum, secjd.intValue());
                        BigDecimal multiply = ERPUtils.getBigDecimal(subqty).multiply(new BigDecimal(10));
                        divide = divide.add(multiply);
                        return divide;
                    } else {
                        BigDecimal divide = qty.multiply(secunitnum).divide(firstunitnum, secjd.intValue());
                        return divide;
                    }
                }
            }
        }else {
            //先去换算第一个计量单位与基本主之间的换算率
            List<MaterialUnitConvet> collect2 = materialUnitConvets.stream().filter(item -> item.getFirstunitid().equalsIgnoreCase(baseUom)).collect(Collectors.toList());
            List<MaterialUnitConvet> collect3 = collect2.stream().filter(item -> item.getSecunitid().equalsIgnoreCase(firstuomid)).collect(Collectors.toList());

            BigDecimal baseQty = BigDecimal.ZERO;

            if(collect3.size()==1){
                MaterialUnitConvet materialUnitConvet = collect3.get(0);
                String convetrule = materialUnitConvet.getConvetrule();
                BigDecimal firstunitnum = materialUnitConvet.getFirstunitnum();
                BigDecimal firstjd = materialUnitConvet.getFirstjd();
                BigDecimal secunitnum = materialUnitConvet.getSecunitnum();
                BigDecimal secjd = materialUnitConvet.getSecjd();
                if (firstunitnum.compareTo(BigDecimal.ZERO) == 0) {
                    throw new RuntimeException("当前物料计量单位换算率定义有问题，请查看物料定义");
                }
                if (convetrule.equalsIgnoreCase("GDHS")) {
                    //固定换算
                    //根据 firstnum * firstQty = secnum * secQty
                    //得到想要的辅数量
                    baseQty = qty.multiply(firstunitnum).divide(secunitnum, firstjd.intValue());
                } else if (convetrule.equalsIgnoreCase("FHHS")) {

                }

                List<MaterialUnitConvet> collect4 = materialUnitConvets.stream().filter(item -> item.getFirstunitid().equalsIgnoreCase(baseUom)).collect(Collectors.toList());
                List<MaterialUnitConvet> collect5 = collect4.stream().filter(item -> item.getSecunitid().equalsIgnoreCase(secuomid)).collect(Collectors.toList());
                if(collect5.size() == 1){
                    MaterialUnitConvet materialUnitConvet1 = collect5.get(0);
                    String convetrule1 = materialUnitConvet1.getConvetrule();
                    BigDecimal firstunitnum1 = materialUnitConvet1.getFirstunitnum();
                    BigDecimal firstjd1 = materialUnitConvet1.getFirstjd();
                    BigDecimal secunitnum1 = materialUnitConvet1.getSecunitnum();
                    BigDecimal secjd1 = materialUnitConvet1.getSecjd();
                    if (firstunitnum1.compareTo(BigDecimal.ZERO) == 0) {
                        throw new RuntimeException("当前物料计量单位换算率定义有问题，请查看物料定义");
                    }
                    if (convetrule1.equalsIgnoreCase("GDHS")) {
                        //固定换算
                        //根据 firstnum * firstQty = secnum * secQty
                        //得到想要的辅数量
                        //   BigDecimal divide = qty.multiply(firstunitnum).divide(secunitnum, Integer.parseInt(secjd.toString()));
                        BigDecimal divide = baseQty.multiply(secunitnum1).divide(firstunitnum1, secjd1.intValue());
                        return divide;
                    } else if (convetrule1.equalsIgnoreCase("FHHS")) {
                        //如果是复合计量单位
                        //判断复合计量单位是否有小数点，如果有小数点的话，将小数点的位置取出来进行单据处理来生成辅数量
                        String sqty = baseQty.toString();
                        if (sqty.contains(".")) {

                            int i = sqty.indexOf(".");
                            String orgqty = sqty.substring(0, i);
                            String subqty = sqty.substring(i, sqty.length());
                            // BigDecimal divide = ERPUtils.getBigDecimal(orgqty).multiply(firstunitnum).divide(secunitnum, Integer.parseInt(secjd.toString()));
                            BigDecimal divide = ERPUtils.getBigDecimal(orgqty).multiply(secunitnum1).divide(firstunitnum1, secjd1.intValue());
                            BigDecimal multiply = ERPUtils.getBigDecimal(subqty).multiply(new BigDecimal(10));
                            divide = divide.add(multiply);
                            return divide;
                        } else {
                            BigDecimal divide = qty.multiply(secunitnum1).divide(firstunitnum1, secjd1.intValue());
                            return divide;
                        }
                    }
                }
            }

        }


        return BigDecimal.ZERO;
    }

    @Override
    @Transactional
    public void importMaterialFromExcel(List<MaterialImportVo> importVos) {

        HashMap<String,Object> uomMap=new HashMap<>();

        for (MaterialImportVo importVo : importVos) {
            Material material = new Material();

            if(importVo.getMaterialcode()==null){
                throw new RuntimeException("物料编号为空，不能导入");
            }

            String materialtypename = importVo.getMaterialtypename();

            if(!ERPUtils.isNoneOrEmpty(materialtypename)){
                Materialtype materialtypebymaterialtypename = materialtypeService.getMaterialtypebymaterialtypename(materialtypename);

                if(materialtypebymaterialtypename==null){
                    throw new RuntimeException("物料类型不存在，请检查！");
                }
                material.setMaterialtypeid(materialtypebymaterialtypename.getId());
            }else{
                throw new RuntimeException("未定义物料类型");
            }

            material.setMaterialcode(importVo.getMaterialcode());

            QueryWrapper<Material> queryWrapper=new QueryWrapper<>();
            queryWrapper.eq("materialcode",material.getMaterialcode());
            List<Material> materials = materialMapper.selectList(queryWrapper);
            if(materials.size()>0){
                throw new RuntimeException("已存在物料编号为："+material.getMaterialcode()+",不允许再次导入!");
            }
            String materialname = importVo.getMaterialname();
            if(ERPUtils.isNoneOrEmpty(materialname)){
                throw new RuntimeException("物料名称不能为空，请检查!");
            }

            material.setMaterialname(materialname);
            String model = importVo.getModel();
            if(!ERPUtils.isNoneOrEmpty(model)){
                material.setModel(model);
            }
            if(!ERPUtils.isNoneOrEmpty(importVo.getSpecs())){
                material.setMspecs(importVo.getSpecs());
            }
            if(ERPUtils.isNoneOrEmpty(importVo.getUomid())){
                throw new RuntimeException("物料编号："+importVo.getMaterialcode()+"基本计量单位不能为空！");
            }
            if(uomMap.containsKey(importVo.getUomid())){
                Scmuom scmuom = (Scmuom) uomMap.get(importVo.getUomid());
                material.setUom(scmuom.getId());
            }else {
                Scmuom scmUomByUomName = scmuomService.getScmUomByUomName(importVo.getUomid());
                if (scmUomByUomName != null) {
                    //存在计量单位
                    uomMap.put(importVo.getUomid(),scmUomByUomName);
                    material.setUom(scmUomByUomName.getId());
                } else {
                    //不存在，则插入计量单位
                    Scmuom scmuom = new Scmuom();
                    scmuom.setUomcode(importVo.getUomid());
                    scmuom.setUomname(importVo.getUomid());
                    scmuom.setUomrate(new BigDecimal(2));
                    scmuomService.save(scmuom);
                    material.setUom(scmuom.getId());
                    uomMap.put(importVo.getUomid(),scmuom);
                }
            }
            material.setLength(importVo.getLength());
            material.setWidth(importVo.getWidth());
            material.setHeight(importVo.getHeight());

            //可销售
            material.setIssale("true");
            material.setIspo("true");
            material.setIsgd("true");

            material.setSecattmatflag("0");
            material.setEnablestatus("0");

            if(uomMap.containsKey(importVo.getWeightuomid())){
                Scmuom scmuom = (Scmuom) uomMap.get(importVo.getWeightuomid());
                material.setWeightuomid(scmuom.getId());
            }else {
                Scmuom weightUom = scmuomService.getScmUomByUomName(importVo.getWeightuomid());
                if (weightUom != null) {
                    material.setWeightuomid(weightUom.getId());
                    uomMap.put(importVo.getWeightuomid(),weightUom);
                } else {
                    Scmuom scmuom = new Scmuom();
                    scmuom.setUomcode(importVo.getWeightuomid());
                    scmuom.setUomname(importVo.getWeightuomid());
                    scmuomService.save(scmuom);
                    material.setWeightuomid(scmuom.getId());
                    uomMap.put(importVo.getWeightuomid(),scmuom);
                }
            }

            if(uomMap.containsKey(importVo.getVolumeuomid())){
                Scmuom o = (Scmuom) uomMap.get(importVo.getVolumeuomid());
                material.setVolumeuomid(o.getId());
            }else {
                Scmuom volumeUom = scmuomService.getScmUomByUomName(importVo.getVolumeuomid());
                if (volumeUom != null) {
                    material.setVolumeuomid(volumeUom.getId());
                    uomMap.put(importVo.getVolumeuomid(),volumeUom);
                } else {
                    Scmuom scmuom = new Scmuom();
                    scmuom.setUomcode(importVo.getVolumeuomid());
                    scmuom.setUomname(importVo.getVolumeuomid());
                    scmuomService.save(scmuom);
                    material.setVolumeuomid(scmuom.getId());
                    uomMap.put(importVo.getVolumeuomid(),scmuom);
                }
            }

            materialMapper.insert(material);

            Materialsale materialsale=new Materialsale();
            materialsale.setParentid(material.getId());
            materialsale.setSaleuomid(material.getUom());
            materialSaleMapper.insert(materialsale);

            Materialpo materialpo=new Materialpo();
            materialpo.setParentid(material.getId());
            materialpo.setPouomid(material.getUom());
            materialPoMapper.insert(materialpo);

            Materialstock materialstock=new Materialstock();
            materialstock.setParentid(material.getId());
            materialstock.setStockuomid(material.getUom());
            materialStockMapper.insert(materialstock);

            Materialmauf materialmauf=new Materialmauf();
            materialmauf.setIsgd("Y");
            materialmauf.setIssale("Y");
            materialmauf.setIspo("Y");
            materialmauf.setParentid(material.getId());
            materialmauf.setIspd("Y");

            materialMaufMapper.insert(materialmauf);

            if(!ERPUtils.isNoneOrEmpty(importVo.getWeightuomid())) {
                MaterialUnitConvet materialUnitConvet = getWeightMaterialUnitConvet(importVo, material);
                materialUnitConvetMapper.insert(materialUnitConvet);
            }

            if(!ERPUtils.isNoneOrEmpty(importVo.getVolumeuomid())) {
                MaterialUnitConvet volumeMaterialUnitConvet = getVolumeMaterialUnitConvet(importVo, material);
                materialUnitConvetMapper.insert(volumeMaterialUnitConvet);
            }
        }
    }

    @Override
    public MaterialVo getMaterialVoInfoByMaterialcode(String materialcode) {
        if(materialcode!=null && materialcode.startsWith("\uFEFF"))
        {
            materialcode=materialcode.substring(1);
        }

//        LambdaQueryWrapper<Material> queryWrapper=new LambdaQueryWrapper<>();
//        queryWrapper.eq(Material::getMaterialcode,materialcode);
        QueryWrapper<Material> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("materialcode",materialcode);
        List<Material> materials = materialMapper.getMaterialByMaterialCode(materialcode);
        if(materials.size() == 0){
            return null;
        }else {
            Material material = materials.get(0);

            MaterialVo materialVo = getMaterialVoInfoByMaterialID(material.getId());
            return materialVo;
        }
    }

    private  MaterialUnitConvet getWeightMaterialUnitConvet(MaterialImportVo importVo, Material material) {
        MaterialUnitConvet materialUnitConvet=new MaterialUnitConvet();
        materialUnitConvet.setParentid(material.getId());
        materialUnitConvet.setConvetrule("GDHS");
        materialUnitConvet.setFirstunitid(material.getUom());
        materialUnitConvet.setSecunitid(material.getWeightuomid());
        materialUnitConvet.setFirstunitnum(new BigDecimal(1));
        materialUnitConvet.setFirstjd(new BigDecimal(3));
        materialUnitConvet.setSecjd(new BigDecimal(3));
        materialUnitConvet.setSecunitnum(ERPUtils.getBigDecimal(importVo.getWeight()));
        return materialUnitConvet;
    }

    private  MaterialUnitConvet getVolumeMaterialUnitConvet(MaterialImportVo importVo, Material material) {
        MaterialUnitConvet materialUnitConvet=new MaterialUnitConvet();
        materialUnitConvet.setParentid(material.getId());
        materialUnitConvet.setConvetrule("GDHS");
        materialUnitConvet.setFirstunitid(material.getUom());
        materialUnitConvet.setSecunitid(material.getVolumeuomid());
        materialUnitConvet.setFirstunitnum(new BigDecimal(1));
        materialUnitConvet.setFirstjd(new BigDecimal(3));
        materialUnitConvet.setSecjd(new BigDecimal(3));
        materialUnitConvet.setSecunitnum(importVo.getVolume());
        return materialUnitConvet;
    }
}
